<template>
  <div class="category-list-container">
    <div class="category-list-header">
      <div class="header-left">
        <h2>分类管理</h2>
        <p class="header-subtitle">共 {{ categories.length }} 个分类</p>
      </div>
      <a-button type="primary" @click="showAddModal" class="add-category-button">
        <template #icon><PlusOutlined /></template>
        新增分类
      </a-button>
    </div>
    
    <a-card class="category-card">
      <a-table
        v-if="!loading && categories.length !== 0"
        :columns="columns"
        :data-source="categories"
        row-key="id"
        :loading="loading"
        :pagination="false"
        class="category-table"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <span class="category-name">{{ record.name }}</span>
          </template>
          <template v-else-if="column.key === 'count'">
            <span class="article-count">
              <a-tag color="blue" class="count-tag">
                {{ record.count || 0 }}
              </a-tag>
            </span>
          </template>
          <template v-else-if="column.key === 'showInNav'">
            <a-tag :color="record.showInNav ? 'green' : 'default'">
              {{ record.showInNav ? '显示' : '隐藏' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'sortOrder'">
            <a-tag color="purple">
              {{ record.sortOrder || 0 }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'createTime'">
            <span>{{ record.createdAt }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space size="middle" class="action-buttons">
              <a-button size="small" @click="handleEdit(record)" class="edit-button">
                <template #icon><EditOutlined /></template>
              </a-button>
              <a-popconfirm
                title="确定要删除这个分类吗？"
                description="删除后该分类下的文章将不受影响，是否继续？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button size="small" danger class="delete-button">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
      
      <!-- 空状态展示 -->
      <div v-if="!loading && categories.length === 0" class="empty-state">
        <div class="empty-icon">📁</div>
        <p class="empty-text">暂无分类数据</p>
        <p class="empty-description">点击上方"新增分类"按钮开始添加</p>
      </div>
    </a-card>
    
    <!-- 新增/编辑分类弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      class="category-modal"
      :transitionName="'fade'"
    >
      <a-form
        :model="categoryForm"
        :rules="categoryRules"
        ref="categoryFormRef"
        layout="vertical"
      >
        <a-form-item name="name" label="分类名称" class="form-item">
          <a-input
            v-model:value="categoryForm.name"
            placeholder="请输入分类名称"
            class="form-input"
            allowClear
          />
        </a-form-item>
        <a-form-item name="description" label="分类描述" class="form-item">
          <a-textarea
            v-model:value="categoryForm.description"
            placeholder="请输入分类描述（选填）"
            :rows="3"
            class="form-textarea"
          />
        </a-form-item>
        <a-form-item name="showInNav" label="显示设置" class="form-item">
          <a-checkbox v-model:checked="categoryForm.showInNav">
            显示在导航栏
          </a-checkbox>
        </a-form-item>
        <a-form-item name="sortOrder" label="优先级" class="form-item">
          <a-input-number
            v-model:value="categoryForm.sortOrder"
            placeholder="请输入优先级（数字越小越靠前）"
            :min="0"
            :max="999"
            class="form-input"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Popconfirm } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import categoryApi from '@/api/category'

const loading = ref(false)
const categories = ref([])
const modalVisible = ref(false)
const modalTitle = ref('新增分类')
const currentCategoryId = ref(null)
const categoryFormRef = ref()
const categoryForm = reactive({
  name: '',
  description: '',
  showInNav: false,
  sortOrder: 0
})

const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 20, message: '分类名称长度在 1 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const isDuplicate = categories.value.some(cat =>
          cat.id !== currentCategoryId.value && cat.name === value
        )
        if (isDuplicate) {
          callback(new Error('分类名称已存在'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  sortOrder: [
    { required: true, message: '请输入优先级', trigger: 'blur' },
    { type: 'number', min: 0, max: 999, message: '优先级范围在 0 到 999', trigger: 'blur' }
  ]
}

const columns = [
  {
    title: '分类名称',
    dataIndex: 'name',
    key: 'name',
    width: 220,
    sorter: (a, b) => a.name.localeCompare(b.name)
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
    width: 350
  },
  {
    title: '文章数量',
    dataIndex: 'count',
    key: 'count',
    width: 120,
    sorter: (a, b) => (a.count || 0) - (b.count || 0)
  },
  {
    title: '显示在导航',
    dataIndex: 'showInNav',
    key: 'showInNav',
    width: 120,
    sorter: (a, b) => (a.showInNav ? 1 : 0) - (b.showInNav ? 1 : 0)
  },
  {
    title: '优先级',
    dataIndex: 'sortOrder',
    key: 'sortOrder',
    width: 100,
    sorter: (a, b) => (a.sortOrder || 0) - (b.sortOrder || 0)
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createTime',
    width: 180,
    sorter: (a, b) => new Date(a.createdAt) - new Date(b.createdAt)
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

const fetchCategories = async () => {
  try {
    loading.value = true
    const response = await categoryApi.getCategories()
    if (response.code === 200 && response.data) {
      // Handle both direct data and nested data structure
      const data = response.data.data || response.data
      categories.value = Array.isArray(data) ? data : []
    }
  } catch (error) {
    message.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

const showAddModal = () => {
  modalTitle.value = '新增分类'
  currentCategoryId.value = null
  categoryForm.name = ''
  categoryForm.description = ''
  categoryForm.showInNav = false
  categoryForm.sortOrder = 0
  modalVisible.value = true
}

const handleEdit = (record) => {
  modalTitle.value = '编辑分类'
  currentCategoryId.value = record.id
  categoryForm.name = record.name
  categoryForm.description = record.description || ''
  categoryForm.showInNav = record.showInNav || false
  categoryForm.sortOrder = record.sortOrder || 0
  modalVisible.value = true
}

const handleModalOk = async () => {
  try {
    await categoryFormRef.value.validate()
    
    let response
    if (currentCategoryId.value) {
      // 编辑分类
      response = await categoryApi.updateCategory(currentCategoryId.value, categoryForm)
    } else {
      // 新增分类
      response = await categoryApi.addCategory(categoryForm)
    }
    
    if (response.code === 200) {
      message.success(currentCategoryId.value ? '编辑成功' : '新增成功')
      modalVisible.value = false
      fetchCategories()
    }
  } catch (error) {
    message.error(error.message || '操作失败，请重试')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  categoryFormRef.value?.resetFields()
}

const handleDelete = async (id) => {
  try {
    const response = await categoryApi.deleteCategory(id)
    if (response.code === 200) {
      message.success('删除成功')
      fetchCategories()
    }
  } catch (error) {
    message.error(error.message || '删除失败')
  }
}

onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.category-list-container {
  width: 100%;
  height: 100%;
  padding: 24px;
}

.category-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 4px;
}

.header-left h2 {
  margin-bottom: 4px;
  color: #262626;
  font-size: 20px;
}

.header-subtitle {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.add-category-button {
  height: 40px;
  font-size: 14px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.add-category-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.category-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  transition: all 0.3s ease;
}

.category-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.category-table {
  border-radius: 8px;
  overflow: hidden;
}

.category-table .ant-table-thead > tr > th {
  background-color: #fafafa;
  font-weight: 500;
  color: #262626;
  border-bottom: 1px solid #f0f0f0;
}

.category-table .ant-table-tbody > tr {
  transition: all 0.3s ease;
}

.category-table .ant-table-tbody > tr:hover > td {
  background-color: #f5f5f5;
}

.category-name {
  font-weight: 500;
  color: #262626;
}

.count-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 20px;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.edit-button,
.delete-button {
  height: 28px;
  font-size: 12px;
  padding: 0 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.edit-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.delete-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(255, 77, 79, 0.3);
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #666;
}

.empty-description {
  font-size: 14px;
  color: #999;
}

/* 弹窗样式 */
.category-modal {
  border-radius: 8px;
}

.form-item {
  margin-bottom: 16px;
}

.form-input,
.form-textarea {
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-input:focus,
.form-textarea:focus {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-list-container {
    padding: 16px;
  }
  
  .category-list-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .add-category-button {
    width: 100%;
  }
  
  .category-table {
    font-size: 12px;
  }
}
</style>